package com.shi.desktop.searcher;

import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.FilterIndexReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocCollector;

public class FileSearcher {

	private static class OneNormsReader extends FilterIndexReader {
		private String field;

		public OneNormsReader(IndexReader in, String field) {
			super(in);
			this.field = field;
		}

		@Override
		public byte[] norms(String field) throws IOException {
			return in.norms(this.field);
		}
	}

	private int numTotalHits;


	
	public FileSearcher() {
	}

	
	public Document[] search(String keyword, int page, int hitsPerPage) throws Exception {
		String index = "d:\\index";
		String field = "content";
		String normsField = null;
		
		IndexReader reader = IndexReader.open(index);
		if(normsField != null) {
			reader = new OneNormsReader(reader, normsField);
		}
		Searcher searcher = new IndexSearcher(reader);
		Analyzer analyzer = new CJKAnalyzer();
		
		QueryParser parser = new QueryParser(field, analyzer);
		Query query = parser.parse(keyword);
		
		TopDocCollector collector = new TopDocCollector(5 * hitsPerPage);
		searcher.search(query, collector);
		numTotalHits = collector.getTotalHits();
		ScoreDoc[] hits = collector.topDocs().scoreDocs;
		if(page > 5) {
			collector = new TopDocCollector(numTotalHits);
			searcher.search(query, collector);
			hits = collector.topDocs().scoreDocs;
		}

		int start = (page - 1) * hitsPerPage;
		int end = ((start + hitsPerPage) > hits.length)?(hits.length - 1):(start + hitsPerPage -1);

		Document[] docs = new Document[end - start + 1];
		for(int i = start; i <= end; i++) {
			docs[i - start] = searcher.doc(hits[i].doc);
		}
		return docs;
	}

	public int getNumTotalHits() {
		return numTotalHits;
	}

}
